package com.yiqi.news.mvp.ui.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.os.PowerManager
import android.support.design.widget.BottomSheetBehavior
import android.support.design.widget.BottomSheetDialog
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.DisplayMetrics
import android.util.Log
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import butterknife.OnClick
import com.github.nukc.stateview.StateView

import com.jess.arms.base.BaseActivity
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.ArmsUtils
import com.jess.arms.widget.DividerItemDecoration
import com.novel.cn.ext.dp2px
import com.yiqi.huize.isNull

import com.yiqi.news.di.component.DaggerNewsDetailComponent
import com.yiqi.news.di.module.NewsDetailModule
import com.yiqi.news.mvp.contract.NewsDetailContract
import com.yiqi.news.mvp.presenter.NewsDetailPresenter

import com.yiqi.news.R
import com.yiqi.news.app.widget.qmui.QMUITipDialog
import com.yiqi.news.entity.NewsDetail
import com.yiqi.news.mvp.ui.adapter.CommentAdapter
import com.yiqi.news.mvp.ui.holder.NewsDetailHeaderView
import kotlinx.android.synthetic.main.activity_news_detail.*
import kotlinx.android.synthetic.main.include_news_detail_tool_bar.*
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.chad.library.adapter.base.BaseQuickAdapter
import com.jess.arms.utils.RxClipboardTool
import com.yiqi.news.BuildConfig
import com.yiqi.news.Constant
import com.yiqi.news.Constant.LIKE_TYPE_COMMENT
import com.yiqi.news.Constant.LIKE_TYPE_NEWS
import com.yiqi.news.Constant.LIKE_TYPE_REPLAY_COMMENT
import com.yiqi.news.app.EventBusTags
import com.yiqi.news.app.service.UserController
import com.yiqi.news.app.utils.SPUtil
import com.yiqi.news.app.utils.SPUtil.SP_NAME
import com.yiqi.news.entity.Comment
import com.yiqi.news.entity.ReplyVO
import com.yiqi.news.mvp.ui.adapter.ReplayCommentAdapter
import com.yiqi.news.wxapi.Login3rdEvent
import com.yiqi.news.wxapi.WechatSdk
import kotlinx.android.synthetic.main.dialog_bottom_sheet_label.view.tv_dialog_close
import kotlinx.android.synthetic.main.diaog_comment.view.*
import kotlinx.android.synthetic.main.diaog_share.view.*
import kotlinx.android.synthetic.main.header_news_detail.*
import kotlinx.android.synthetic.main.header_news_detail.view.*
import org.simple.eventbus.EventBus
import java.util.*
import kotlinx.android.synthetic.main.header_news_detail.view.tv_comment_count as tv_comment_count1


@Suppress("DEPRECATION")
class NewsDetailActivity : BaseActivity<NewsDetailPresenter>(), NewsDetailContract.View, TextView.OnEditorActionListener, BaseQuickAdapter.OnItemChildClickListener {


    /**
     * 上次检查时间，用于在运行时作为基准获取用户时间
     */
    var lastCheckTime: Long = 0
    /**
     * 前台Activity数量
     */
    private var foregroundActivityCount = 0
    /**
     * Activity是否在修改配置，
     */
    private var isChangingConfigActivity = false
    /**
     * 应用将要切换到前台
     */
    private var willSwitchToForeground = false
    /**
     * 当前是否在前台
     */
    private var isForegroundNow = false


    private val bottomSheetBehavior by lazy {
        return@lazy BottomSheetBehavior.from(mCommentView.parent as View)
    }

    /**
     * 上次暂停的Activity信息
     */
    private var lastPausedActivityName: String? = null
    private var lastPausedActivityHashCode: Int = 0
    private var lastPausedTime: Long = 0
    private var appUseReduceTime: Long = 0
    /**
     * 每次有Activity启动时的开始时间点
     */
    private var appStartTime = 0L

    /**
     * 是否阅读完（webview滚动到底部）
     */
    private var isReadEnd = false

    /**
     * 本次统计时，运行的时间
     */
    private var runTimeThisDay = 0L

    //////////////////////以上变量为阅读时间统计变量/////////////////////////
    private lateinit var mCommentView: View
    private var isZan: Int = 0
    private var isCollect: Int = 0

    private lateinit var mNewsDetail: NewsDetail

    private val mBottomSheetDialog: BottomSheetDialog by lazy {
        return@lazy BottomSheetDialog(this)
    }
    private val mCommentDialog: BottomSheetDialog by lazy {
        return@lazy BottomSheetDialog(this)
    }
    private val mStateView: StateView by lazy {
        return@lazy StateView.inject(fl_content_detail)
    }

    private val mNewsId: String by lazy {
        return@lazy intent.getStringExtra("news_id")
    }

    private val mHeaderView: NewsDetailHeaderView by lazy {
        return@lazy NewsDetailHeaderView(this)
    }


    private val mCommentAdapter: CommentAdapter by lazy {
        return@lazy CommentAdapter()
    }

    private val mReplayCommentAdapter: ReplayCommentAdapter by lazy {
        return@lazy ReplayCommentAdapter()
    }


    private val mWechatSdk: WechatSdk by lazy {
        return@lazy WechatSdk(this, BuildConfig.APP_ID_WECHAT)
    }

    private fun showDialog(msg: String) {
        val mCopyDialog: QMUITipDialog by lazy {
            return@lazy QMUITipDialog.Builder(this)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                    .setTipWord(msg)
                    .create()
        }

        mCopyDialog.show()
    }

    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerNewsDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .newsDetailModule(NewsDetailModule(this))
                .build()
                .inject(this)
    }


    override fun initView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_news_detail //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    override fun initEvent() {
        edt_news_comment.setOnEditorActionListener(this)
        initBottomSheetDialog()
//        initCommentDialog(mCommentAdapter.getItem(mSelectPosition)!!)
    }


    override fun showNewsRefresh(news: NewsDetail) {
        mNewsDetail = news
        mCommentAdapter.setNewData(mNewsDetail.materialCommentVoList)
    }


    override fun showNewsDetail(news: NewsDetail) {
        mNewsDetail = news
        setDetailData(mNewsDetail)
        mCommentAdapter.setNewData(mNewsDetail.materialCommentVoList)
        mHeaderView.setDetail(news) {
            //加载完成后，显示内容布局
            mStateView.showContent()
        }


        val resources = this.resources
        val dm = resources.displayMetrics
        val height = dm.heightPixels
        rv_comment_news.viewTreeObserver.addOnGlobalLayoutListener {
            rv_comment_news.viewTreeObserver.removeGlobalOnLayoutListener { }
            isReadEnd = mCommentAdapter.headerLayout.height <= height

            Log.d("qaq", "高度" + rv_comment_news.bottom + "-----屏幕高度：" + height + "sssss:" + mCommentAdapter.headerLayout.height)
        }

    }


    private fun setDetailData(news: NewsDetail) {
        isZan = news.isZan
        isCollect = news.isCollect
        btn_news_like.setImageResource(if (isZan == 1) R.mipmap.ic_toolbar_news_like else R.mipmap.ic_toolbar_news_dislike)
        btn_news_collection.setImageResource(if (isCollect == 1) R.mipmap.ic_toolbar_collected else R.mipmap.ic_toolbar_news_collection)
    }

    override fun showLikeDialogCommentSucess(position: Int) {
        setReplayCommentData(position)
    }

    override fun showCommentReply(data: List<ReplyVO>) {

    }

    override fun showNewsError(error: String) {
        mStateView.showRetry()
    }


    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            ArmsUtils.hidekeyboard(this)

            if (mNewsDetail != null) {
                if (UserController.getInstance().isLogin && !mNewsDetail.isNull()) mPresenter?.doCommentNews(mNewsDetail?.id, mNewsDetail?.materialType, edt_news_comment.text.toString().trim()) else ArmsUtils.startActivity(LoginActivity::class.java)
            }
            return true
        }
        return false

    }

    override fun showCommentSucess() {
        edt_news_comment.setText("")
        mPresenter?.getNewsData(mNewsId, false)

        rv_comment_news.scrollToPosition(1)
        showDialog(getString(R.string.dialog_comment_success))
    }

    override fun showLikeSucess(type: Int) {
        if (isZan == 0) {
            isZan = 1
            btn_news_like.setImageResource(R.mipmap.ic_toolbar_news_like)
//            if (mCommentView != null) mCommentView.btn_comment_like.setImageResource(R.mipmap.ic_toolbar_news_like)
            mNewsDetail.newsZanCount++
            mHeaderView.tv_like.text = "点赞" + mNewsDetail.newsZanCount.toString()
        } else {
            isZan = 0
            btn_news_like.setImageResource(R.mipmap.ic_toolbar_news_dislike)
//            if (mCommentView != null) mCommentView.btn_comment_like.setImageResource(R.mipmap.ic_toolbar_news_dislike)
            mNewsDetail.newsZanCount--
            mHeaderView.tv_like.text = "点赞" + mNewsDetail.newsZanCount.toString()
        }
    }

    override fun showLikeCommentSucess(position: Int) {
        setCommentData(position)
    }


    private fun setCommentData(position: Int) {
        var comment = mCommentAdapter.getItem(position)
        if (!comment?.haveZan.isNullOrEmpty() && comment?.haveZan.equals("1")) {
            comment?.haveZan = "0"
            comment?.commentZanCount = comment?.commentZanCount?.minus(1)!!
        } else {
            comment?.haveZan = "1"
            comment?.commentZanCount = comment?.commentZanCount?.plus(1)!!
        }

        if (comment != null) {
            mCommentAdapter.run { setData(position, comment) }
        }
    }

    private fun setReplayCommentData(position: Int) {
        var item = mReplayCommentAdapter.getItem(position)
        if (!item?.haveZan.isNullOrEmpty() && item?.haveZan.equals("1")) {
            item?.haveZan = "0"
            item?.commentZanCount = item?.commentZanCount?.minus(1)!!
        } else {
            item?.haveZan = "1"
            item?.commentZanCount = item?.commentZanCount?.plus(1)!!
        }

        if (item != null) {
            mReplayCommentAdapter.run { setData(position, item) }
        }
    }

    override fun showCollectionSucess() {
        if (isCollect == 0) {
            isCollect = 1
            btn_news_collection.setImageResource(R.mipmap.ic_toolbar_collected)
        } else {
            isCollect = 0
            btn_news_collection.setImageResource(R.mipmap.ic_toolbar_news_collection)
        }
    }

    override fun showError(error: String) {
        showMessage(error)
    }


    override fun onStart() {
        super.onStart()


        //前台没有Activity，说明新启动或者将从从后台恢复
        if (foregroundActivityCount == 0 || !isForegroundNow) {
            willSwitchToForeground = true
        } else {
            //应用已经在前台，此时保存今日运行的时间。
            runTimeThisDay = System.currentTimeMillis() - appStartTime
            lastCheckTime = System.currentTimeMillis()
            saveTodayPlayTime(this, runTimeThisDay)
        }
        appStartTime = System.currentTimeMillis()
        if (isChangingConfigActivity) {
            isChangingConfigActivity = false
            return
        }
        foregroundActivityCount += 1
    }

    override fun onResume() {
        super.onResume()


        //在这里更新检查时间点，是为了保证从后台恢复到前台，持续计时的准确性。
        lastCheckTime = System.currentTimeMillis()
        addAppUseReduceTimeIfNeeded(this)
        if (willSwitchToForeground && isInteractive(this)) {
            isForegroundNow = true
        }
        if (isForegroundNow) {
            willSwitchToForeground = false
        }
    }

    private fun addAppUseReduceTimeIfNeeded(activity: Activity) {
        if (getActivityName(activity) == lastPausedActivityName && activity.hashCode() == lastPausedActivityHashCode) {
            val now = System.currentTimeMillis()
            if (now - lastPausedTime > 1000) {
                appUseReduceTime += now - lastPausedTime
            }
        }
        lastPausedActivityHashCode = -1
        lastPausedActivityName = null
        lastPausedTime = 0
    }

    private fun isInteractive(context: Context): Boolean {
        val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            pm.isInteractive
        } else {
            pm.isScreenOn
        }
    }

    override fun onPause() {
        super.onPause()


        lastPausedActivityName = getActivityName(this)
        lastPausedActivityHashCode = this.hashCode()
        lastPausedTime = System.currentTimeMillis()
    }

    override fun onStop() {
        super.onStop()


        addAppUseReduceTimeIfNeeded(this)
        //如果这个Activity实在修改配置，如旋转等，则不保存时间直接返回
        if (this.isChangingConfigurations) {
            isChangingConfigActivity = true
            return
        }
        //该Activity要进入后台，前台Activity数量-1。
        foregroundActivityCount -= 1
        //当前已经是最后的一个Activity，代表此时应用退出了，保存时间。
        // 如果跨天了，则从新一天的0点开始计时
        if (foregroundActivityCount == 0) {
            isForegroundNow = false

            runTimeThisDay = if (getTodayStartTime() > appStartTime) {
                System.currentTimeMillis() - getTodayStartTime()
            } else {
                System.currentTimeMillis() - appStartTime
            }
            saveTodayPlayTime(this, runTimeThisDay)
            lastCheckTime = System.currentTimeMillis()

        }
    }

    override fun initData(savedInstanceState: Bundle?) {


        mStateView.setLoadingResource(R.layout.page_loading)
        mStateView.setRetryResource(R.layout.page_net_error)
        mStateView.showLoading()

        rv_comment_news.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(dp2px(18)))
        mCommentAdapter.bindToRecyclerView(rv_comment_news)
        mCommentAdapter.setHeaderView(mHeaderView)
        mCommentAdapter.onItemChildClickListener = this




        rv_comment_news.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (!recyclerView.canScrollVertically(1)) {
                    isReadEnd = true
                }
            }
        })

        mCommentView = LayoutInflater.from(this).inflate(R.layout.diaog_comment, null, false)
        mCommentDialog.setContentView(mCommentView)

//        (mCommentView.parent as View).setBackgroundColor(resources.getColor(android.R.color.transparent))
        mCommentView.tv_dialog_close.setOnClickListener { mCommentDialog.dismiss() }
        mCommentView.rv_dialog_comment.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(dp2px(2)))

        mReplayCommentAdapter.bindToRecyclerView(mCommentView.rv_dialog_comment)



        mPresenter?.getNewsData(mNewsId)

    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (view?.id) {
            R.id.btn_comment_like_count -> if (UserController.getInstance().isLogin) mCommentAdapter.getItem(position)?.id?.let { mPresenter?.doLikeComment(LIKE_TYPE_COMMENT, it, position) } else ArmsUtils.startActivity(LoginActivity::class.java)
            R.id.iv_comment_comment, R.id.tv_reply -> {
                initCommentDialog(adapter?.getItem(position) as Comment)
                mCommentDialog.show()
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED)
            }
        }
    }

    override fun showMessage(message: String) {
        mCommentView.edt_news_dialog_comment.setText("")
        mPresenter?.getNewsData(mNewsId, false)
        showDialog(message)
//        ArmsUtils.snackbarText(message)

    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(R.id.toolbar).init()
    }


    private fun initBottomSheetDialog() {
        var mView = LayoutInflater.from(this).inflate(R.layout.diaog_share, null, false)
        mBottomSheetDialog.setContentView(mView)
        (mView.parent as View).setBackgroundColor(resources.getColor(android.R.color.transparent))
        mView.tv_dialog_close.setOnClickListener { mBottomSheetDialog.dismiss() }
        mView.btn_share_link.setOnClickListener {
            RxClipboardTool.copyText(this, mNewsDetail?.shareUrl)
            showDialog(getString(R.string.dialog_copy_success))
            mBottomSheetDialog.dismiss()
        }
        mView.btn_share_wechat.setOnClickListener {
            if (mNewsDetail != null)
                mWechatSdk.share(mNewsDetail.title, mNewsDetail.title, mNewsDetail.image, mNewsDetail.shareUrl, SendMessageToWX.Req.WXSceneSession)
            mBottomSheetDialog.dismiss()
        }
    }

    @OnClick(R.id.btn_news_like, R.id.btn_news_share, R.id.btn_news_collection)
    fun onClick(view: View) {
        when (view.id) {
            R.id.btn_news_like -> if (UserController.getInstance().isLogin && !mNewsDetail.isNull()) mPresenter?.doLikeNews(LIKE_TYPE_NEWS, mNewsId) else ArmsUtils.startActivity(LoginActivity::class.java)
            R.id.btn_news_share -> mBottomSheetDialog.show()
            R.id.btn_news_collection -> if (UserController.getInstance().isLogin) mPresenter?.doNewsCollection(mNewsId) else ArmsUtils.startActivity(LoginActivity::class.java)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null || data.extras == null) {
            return
        }
        EventBus.getDefault().post(Login3rdEvent(requestCode, resultCode, data), EventBusTags.LOGIN_3_RDEVENT)
    }


    private fun initCommentDialog(comment: Comment?) {
        var num = 0
        if (comment == null || comment.ratingReplyVoList.isNullOrEmpty()) {
            num = 0
        } else {
            num = comment.ratingReplyVoList.size
        }

        mCommentView.tv_comment_count.text = "${num}条回复"
        mReplayCommentAdapter.onItemChildClickListener = BaseQuickAdapter.OnItemChildClickListener { adapter, view, position ->
            mPresenter?.doLikeDialogComment(LIKE_TYPE_REPLAY_COMMENT, comment!!.id, position)
        }


//        mCommentView.btn_comment_like.setImageResource(if (!haveZan.isNullOrEmpty() && haveZan == "1") R.mipmap.ic_toolbar_news_like else R.mipmap.ic_toolbar_news_dislike)
        mCommentView.tv_release.setOnClickListener {
            ArmsUtils.hideKeyboard(mCommentView.edt_news_dialog_comment)
            var data = mCommentView.edt_news_dialog_comment.text.toString().trim()
            mPresenter?.requestReplyMessage(comment?.id!!, data, comment?.fromUserid!!)
            mCommentDialog.dismiss()
//            if (UserController.getInstance().isLogin) mCommentAdapter.getItem(mSelectPosition)?.id?.let { mPresenter?.doLikeComment(LIKE_TYPE_COMMENT, it) } else ArmsUtils.startActivity(LoginActivity::class.java)
        }
        mCommentView.edt_news_dialog_comment.setOnEditorActionListener { v, actionId, event ->
            ArmsUtils.hideKeyboard(mCommentView.edt_news_dialog_comment)
            if (mNewsDetail != null) {
                var data = mCommentView.edt_news_dialog_comment.text.toString().trim()
                mPresenter?.requestReplyMessage(comment?.id!!, data, comment?.fromUserid!!)
                mCommentDialog.dismiss()
//                if (UserController.getInstance().isLogin && !mNewsDetail.isNull()) mPresenter?.doCommentNews(mNewsDetail?.id, mNewsDetail?.materialType, mCommentView.edt_news_dialog_comment.text.toString().trim()) else ArmsUtils.startActivity(LoginActivity::class.java)
            }
            false
        }


        mReplayCommentAdapter.setNewData(comment?.ratingReplyVoList)


    }

    override fun onDestroy() {
        super.onDestroy()
        if (isReadEnd) {
            EventBus.getDefault().post(Message(), EventBusTags.UPDATE_GOLD)
        } else {
            EventBus.getDefault().post(Message(), EventBusTags.UPDATE_TIME)
        }
    }


    private fun getActivityName(activity: Activity): String {
        return activity.javaClass.canonicalName
    }

    /**
     * 获取今日0点的时间点，/1000*1000保证每次取值相同。
     *
     * @return
     */
    fun getTodayStartTime(): Long {
        val calendar = Calendar.getInstance()
        calendar.time = Date()
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        return calendar.timeInMillis / 1000 * 1000
    }

    /**
     * 保存今日运行时间，以今日0点的时间作为Key值。
     *
     * @param context
     * @param time
     */
    private fun saveTodayPlayTime(context: Context, time: Long) {
        val todayTime = SPUtil.getLong(context, SP_NAME, getTodayStartTime().toString(), 0)

        SPUtil.put(context, SP_NAME, getTodayStartTime().toString(), todayTime + time)
        val yesterdayTime = SPUtil.getLong(context, SPUtil.SP_NAME_INJOY, (getTodayStartTime() - Constant.ONE_DAY).toString(), 0)
        //清除前一天的值
        if (yesterdayTime > 0) {
            SPUtil.remove(context, SPUtil.SP_NAME_INJOY,
                    (getTodayStartTime() - Constant.ONE_DAY).toString())
        }
    }
}
